<?php
require_once("libs/general_inc.php");

class Agent extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        $sql = new sql();
        $sql->connect();
        $GENOBJ = new generalFunction();
        $fetchAgent = array();
        authentication();
        $sql = new sql();
        $sql->connect();
        $getPage = getPage();
        $this->view->getPage = $getPage[0];
        $dateTime = DateTime();
        $this->view->template = $sql->fetchAll("template", array("1" => '1'));

        $errorArray = Array();
        $ag_name = '';
        $ag_email = '';
        $ag_phone_no = '';
        $ag_status = '';


        if (isset($_POST['delete'])) {
            for ($i = 0; $i < count($_POST['ag_id']); $i++) {

                $arraydata = array(
                    "ag_status" => 2,
                );
                $update = $sql->update('tbl_agent', $arraydata, array("ag_id" => $_POST['ag_id'][$i]));
            }
            if ($update) {
                header("Location: " . URL . "agent/?action=view&reply=AgentDeleted");
            } else {
                header("Location: " . URL . "agent/?action=view&reply=PageError");
            }
        }

        function ValidEmailAddress($EmailAddress) {
            if (!preg_match("/^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i", $EmailAddress)) {
                return false;
            }
            return true;
        }

        if (GET('action') == 'add') {
            if (isset($_POST['submit'])) {

                $ag_name = $_POST['ag_name'];
                $ag_email = $_POST['ag_email'];
                $ag_phone_no = $_POST['ag_phone_no'];
                $ag_status = $_POST['ag_status'];
                if ($ag_name == '') {
                    $errorArray[] = 'Please enter agent name';
                } else if ($ag_email == '') {
                    $errorArray[] = 'Please enter agent email';
                } else if ($ag_email != '' && ValidEmailAddress($ag_email) != 1) {
                    $errorArray[] = 'Please enter valid email';
                } else if ($ag_phone_no == '') {
                    $errorArray[] = 'Please enter phone number';
                }else{
                    $chek_email_unique = $sql->fetch("tbl_agent", array("ag_email" => $ag_email));
                    if($chek_email_unique['ag_id'] != '' ){
                        $errorArray[] = 'Already exists.please use another email';
                    }
                    $chek_phone_unique = $sql->fetch("tbl_agent", array("ag_phone_no" => $ag_phone_no));
                    if($chek_phone_unique['ag_id'] != '' ){
                        $errorArray[] = 'Already exists.please use another conatct';
                    }
                }
                
                
                
                if (count($errorArray) > 0) {
                    
                } else {
                    
                    
                    $arraydata = array("ag_name" => $_POST['ag_name'],
                        "ag_email" => $_POST['ag_email'],
                        "ag_phone_no" => $_POST['ag_phone_no'],
                        "ag_status" => $_POST['ag_status'],
                        "ag_createdate" => date('Y-m-d h:i:s'),
                        "ag_updatedate" => date('Y-m-d h:i:s'),
                        "LastModifyBy" => base64_decode($_COOKIE['login_user_uid']),
                    );
                    $filterArray = Array("TrimElement", "htmlEntity");  
                    $filterElements = $GENOBJ->filter($arraydata, $filterArray);
                
                    $insert = $sql->insert('tbl_agent', $filterElements);
                    if ($insert) {
                        header("Location: " . URL . "agent/?action=view&reply=AgentCreated");
                    } else {
                        header("Location: " . URL . "agent/?action=view&reply=AgentError");
                    }
                }
                $this->view->ag_name = $ag_name;
                $this->view->ag_email = $ag_email;
                $this->view->ag_phone_no = $ag_phone_no;
                $this->view->ag_status = $ag_status;
            }
            $this->view->ErrorMessage = $errorArray;
        }

        if (isset($_POST['submit']) and isset($_POST['editUid'])) {
            $ag_name = $_POST['ag_name'];
            $ag_email = $_POST['ag_email'];
            $ag_phone_no = $_POST['ag_phone_no'];
            $ag_status = $_POST['ag_status'];

            if ($ag_name == '') {
                $errorArray[] = 'Please enter agent name';
            } else if ($ag_email == '') {
                $errorArray[] = 'Please enter agent email';
            } else if ($ag_email != '' && ValidEmailAddress($ag_email) != 1) {
                $errorArray[] = 'Please enter valid email';
            } else if ($ag_phone_no == '') {
                $errorArray[] = 'Please enter phone number';
            }else{
                    $query_email = "SELECT * FROM tbl_agent WHERE ag_id != ".$_POST['editUid']." and ag_email='".$ag_email."'" ;   
                    $chek_email_unique = $sql->fetchSimpleData($query_email);
                    $query_phone = "SELECT * FROM tbl_agent WHERE ag_id != ".$_POST['editUid']." and ag_phone_no='".$ag_phone_no."'" ;   
                    $chek_phone_unique = $sql->fetchSimpleData($query_phone);
                    if(count($chek_email_unique) > 0 ){
                        $errorArray[] = 'Already exists.please use another email';
                    }
                    if(count($chek_phone_unique) > 0  ){
                        $errorArray[] = 'Already exists.please use another conatct';
                    }
                }
            if (count($errorArray) > 0) {
                
            } else {
                $arraydata = array("ag_name" => $_POST['ag_name'],
                    "ag_email" => $_POST['ag_email'],
                    "ag_phone_no" => $_POST['ag_phone_no'],
                    "ag_status" => $_POST['ag_status'],
                    "ag_updatedate" => date('Y-m-d h:i:s'),
                    "LastModifyBy" => base64_decode($_COOKIE['login_user_uid']),
                );
                //$update=$sql->update('page',array("permalink"=>$permalink),array("uid"=>$_POST['editUid']));
                $filterArray = Array("TrimElement", "htmlEntity");  
                $filterElements = $GENOBJ->filter($arraydata, $filterArray);
                
                $update = $sql->update('tbl_agent', $filterElements, array("ag_id" => $_POST['editUid']));
                if ($update) {
                    header("Location: " . URL . "agent/?action=view&reply=AgentUpdated");
                } else {
                    header("Location: " . URL . "agent/?action=view&reply=AgentError");
                }
            }


            $this->view->ag_name = $ag_name;
            $this->view->ag_email = $ag_email;
            $this->view->ag_phone_no = $ag_phone_no;
            $this->view->ag_status = $ag_status;
            $this->view->ErrorMessage = $errorArray;
        }



        if (GET('action') == 'view') {
            $page = (int) (GET("page") ? GET("page") : 1 );
            if (GET('search')) {
                $statement = "tbl_agent where ag_status!=2 and  ag_name like '%" . GET('q') . "%' order by ag_id desc";
                $this->view->oldData = "action=" . GET('action') . "&q=" . GET('q') . "search=" . GET('q');
            } else {
                $statement = "tbl_agent where ag_status!=2 order by ag_id desc";
                $this->view->oldData = "action=" . GET('action');
            }
            $limit = 50;
            $fetchAgent = $sql->PagingNationFetch($statement, $page, $limit);
            $this->view->statement = $statement;
            $this->view->limit = $limit;
            $this->view->page = $page;
            $this->view->PagingNationFetch = $fetchAgent;
        } else if (GET('action') == 'report') {
            $FinalAgentArray = array();
            $page = (int) (GET("page") ? GET("page") : 1 );
            $fetchAgentOrderData = array();
            $errorArray = Array();
            $start_date = '';
            $end_date = '';
            $agent_id = '';
            $statement = '';
            $limit = '';
            $GETID = getId();

            function IsValidDate($str) {
                $stamp = strtotime($str);

                if (!is_numeric($stamp)) {
                    return FALSE;
                }
                $month = date('m', $stamp);
                $day = date('d', $stamp);
                $year = date('Y', $stamp);

                if (checkdate($month, $day, $year)) {
                    return TRUE;
                }

                return FALSE;
            }

            function IsGreaterDate($date, $expiry_date) {
                $date = strtotime($date);
                $expiry_date = strtotime($expiry_date);
                if ($expiry_date > $date) {
                    return FALSE;
                }
                return TRUE;
            }

            if (GET('submit_report')) {
                // echo 'in';exit;
                // $FinalAgentArray = array();
                $start_date = GET('start_date');
                $end_date = GET('end_date');
                $agent_id = GET('ag_id');



                /* if($agent_id == ''){
                  $errorArray[] = 'Please select agent';
                  }else */
                if ($start_date == '') {
                    $errorArray[] = 'Please select start date';
                } else if ($start_date != '' && IsValidDate($start_date) != 1) {
                    $errorArray[] = 'Please enter valid date';
                } else if ($end_date == '') {
                    $errorArray[] = 'Please select end date';
                } else if ($end_date != '' && IsValidDate($end_date) != 1) {
                    $errorArray[] = 'Please enter valid date';
                } else if (IsGreaterDate($end_date, $start_date) != 1) {
                    $errorArray[] = 'Please select enddate to greater than of startdate';
                }

                if (count($errorArray) > 0) {
                    
                } else {
                    //  $FinalAgentArray = array();
                    $statement = "payment_order as pt join tbl_agent as ag ON ag.ag_id = pt. 	pt_agent_id where date(pt_createDate) BETWEEN '" . $start_date . "' and '" . $end_date . "'  group by pt_agent_id ";
                    $limit = 10;
                    $fetchAgentOrderData = $sql->PagingNationFetch($statement, $page, $limit);


                    foreach ($fetchAgentOrderData as $ag_key => $ag_value) {
                        $statement1 = "select * from payment_order as pt where pt_agent_id = '" . $ag_value['pt_agent_id'] . "'  and date(pt_createDate) BETWEEN '" . $start_date . "' and '" . $end_date . "'";
                        $payment_count = $sql->fetchSimpleData($statement1);

                        //$payment_count = $sql->fetchAll("payment_order", array("pt_agent_id" => 
                        //$ag_value['pt_agent_id'],'date(pt_createDate) BETWEEN "'.$start_date.'" and "'.$end_date.'"'));

                        $total_Amount = '';
                        foreach ($payment_count as $p_key => $p_value) {
                            $total_Amount += $p_value['pt_total_amount'];
                        }


                        $FinalAgentArray[$ag_key]['ag_name'] = $ag_value['ag_name'];
                        $FinalAgentArray[$ag_key]['payment_count'] = count($payment_count);
                        $FinalAgentArray[$ag_key]['total_amount'] = $total_Amount;
                    }
                }
            }

            //echo '<prE>';
            //print_R($payment_count);


            $agentArray = array();
            $agentArray = $sql->fetchAll("tbl_agent", array("ag_status" => 1));

            $this->view->start_date = $start_date;
            $this->view->end_date = $end_date;
            $this->view->agent_id = $agent_id;

            $this->view->oldData = "action=" . GET('action') . "&ag_id=" . $agent_id . "&start_date=" . $start_date . "&end_date=" . $end_date . "&submit_report=Submit";
            $this->view->statement = $statement;
            $this->view->limit = $limit;
            $this->view->page = $page;
            $this->view->agentArray = $agentArray;
            $this->view->fetchAgentOrderData = $FinalAgentArray;
            $this->view->ErrorMessage = $errorArray;
        } elseif (GET('action') == 'edit') {
            $this->view->editrow = $sql->fetch("tbl_agent", array("ag_id" => GET('editUid')));
            $this->view->ErrorMessage = $errorArray;
        }


        if (GET('reply')) {
            $this->view->noti = msg(GET('reply'));
        }

        if (checkPermission('premission_agent')) {
            $this->view->render('agent');
        } else {
            $this->view->render('permission_denied');
        }
    }

}

